﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BestBuy.DAL;
using BestBuy.Common;
namespace BestBuy.PageUser
{
    public partial class MbCompany : System.Web.UI.Page
    {
        private static String pto;
        private static String bro;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["IDDN"].ToString().Equals(""))
            {
                Response.Redirect("~/Account/Login.aspx");
            }
            if (!IsPostBack)
            {
                YearLoad();
                IndustryLoad();
                LoadInfoCompany();
            }
        }
        private Boolean dk1 = true;
        private Boolean dk2 = true;
        private Boolean dk3 = true;
        private Boolean dk4 = true;
        private Boolean dk5 = true;
        private Boolean dk6 = true;
        private Boolean dk7 = true;
        const int MaxQuantity = 3;        
        private void YearLoad()
        {
            for (int i = 1885; i <= 2013; i++)
            {
                cbYear.Items.Add(i.ToString());
            }
        }
        private void IndustryLoad()
        {
            var kq = CCongTy.getParentCategory();
            cbIndustry.DataSource = kq;
            cbIndustry.DataBind();         
        }
        public Boolean checkCompany()
        {
            if (txtCompany.Text != "")
            {
                return true;
            }
            else
                return false;
        }
        public Boolean checkMainMarket()
        {
            Boolean flag = false;
            for (int i = 0; i < ChecklistMarket.Items.Count;i++ )
            {
                if (ChecklistMarket.Items[i].Selected ==true)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        public Boolean checkKeyProduct()
        {
            if (txtKeyProduct.Text!="")
            {
                return true;
            } 
            else
            {
                return false;
            }
        }
        public Boolean checkIntroduce()
        {
            if (txtIntroduct.Text != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public Boolean checkCategory()
        {
            if (CategoryListBox.Items.Count!=0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private Boolean checkBusiness()
        {
            if (cbEmployees.SelectedItem.Value == "")
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        private Boolean checkEmployess()
        {
            if (cbEmployees.SelectedItem.Value == "")
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        private void LoadInfoCompany()
        {
            int idCompany = CCongTy.getIdCompany(int.Parse(Session["IDDN"].ToString()));
            CongTy ct = CCongTy.getInfo(idCompany);
            txtCompany.Text = ct.TenCongTy;
            cbBusiness.SelectedItem.Text = ct.LoaiCongTy;
            String[] main = ct.ThiTruongChinh.Split('+');
            for (int i = 0; i < ChecklistMarket.Items.Count-1;i++ )
            {
                if (main[i] == "1")
                {
                    ChecklistMarket.Items[i].Selected = true;
                }
            }
            cbIndustry.SelectedItem.Value= ct.IDNganh.ToString();
            txtKeyProduct.Text = ct.TuKhoaSanPham;
            List<DanhMucCongTy> listct = CCongTy.getAllCategoryCompany(idCompany);            
            for (int i=0; i<listct.Count;i++)
            {
                ListItem item = new ListItem();
                DanhMuc dm = CCongTy.getItem(listct[i].IDDanhMuc);
                item.Value = dm.IDDanhMuc.ToString();
                item.Text = dm.TenDanhMuc;
                CategoryListBox.Items.Add(item);
            }
            cbEmployees.SelectedItem.Text = ct.SoLuongNhanVien;
            cbYear.SelectedItem.Text = ct.NamThanhLap.ToString();
            txtIntroduct.Text = ct.GioiThieuCongTy;
            txtWebsite.Text = ct.TrangCongTy;
            if (ct.LogoCongTy!=null)
            {
                ImageLogo.Visible = true;
                ImageLogo.ImageUrl = "~/Images/Product/" + ct.LogoCongTy;
                pto = ct.LogoCongTy;
            }            
            txtBrochoure.Text = ct.TaiLieu;
            bro = ct.TaiLieu;
            txtLocation.Text = ct.KhuVucNhaMay;
            if (ct.KichThuocNhaMay != null)
            {
                cbFactorySize.SelectedItem.Text = ct.KichThuocNhaMay;
            }
            if (ct.TongSoBanHangNam!=null)
            {
                cbTotalAnnual.SelectedItem.Text = ct.TongSoBanHangNam;
            }
            if (ct.SoLuongNhanVienRD!=null)
            {
                cbRDStaff.SelectedItem.Text = ct.SoLuongNhanVienRD;
            }
            if (ct.SoLuongNhanVienQC != null)
            {
                cbQCStaff.SelectedItem.Text = ct.SoLuongNhanVienQC;
            }
            txtCertificate.Text = ct.GiayChungNhan;
            if (ct.HopDongSanXuat != null)
            {
                String[] strHD = ct.HopDongSanXuat.Split('+');
                for (int i = 0; i < CheckBoxListContract.Items.Count -1;i++ )
                {
                    if (strHD[i] =="1")
                    {
                        CheckBoxListContract.Items[i].Selected = true;
                    }
                }
            }
            if (ct.VonDieuLe!=null)
            {
                cbRegisterCapital.SelectedItem.Text = ct.VonDieuLe;
            }
            if (ct.LoaiQuyenSoHuu!=null)
            {
                cbOwnership.SelectedItem.Text = ct.LoaiQuyenSoHuu;
            }
            if (ct.NguoiDaiDien!=null)
            {
                txtLegalRepresentative.Text = ct.NguoiDaiDien;
            }
            if (ct.TongSoBanHangNam!=null)
            {
                cbTotalAnnualSale.SelectedItem.Text = ct.TongSoBanHangNam;
            }
            if (ct.TyLeXuatKhau != null)
            {
                txtExportPercentage.Text = ct.TyLeXuatKhau;
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            dk1 = checkBusiness();
            dk2 = checkEmployess();
            dk3 = checkCompany();
            dk4 = checkMainMarket();
            dk5 = checkKeyProduct();
            dk6 = checkIntroduce();
            dk7 = checkCategory();
            
            if (dk1 ==false)
            {
                lbEmployee.Visible = true;
            }
            else
            {
                lbEmployee.Visible = false;
            }
            if (cbBusiness.SelectedItem.Value == "")
            {
                dk2 = false;
            }
            if (dk2 == false)
            {
                lbbusiness.Visible = true;
            }
            else
            {
                lbbusiness.Visible = false;
            }
            if (dk3 == false)
            {
                lbCompany.Visible = true;
            }
            else
            {
                lbCompany.Visible = false;
            }
            if (dk4 == false)
            {
                lbmarket.Visible = true;
            }
            else
            {
                lbmarket.Visible = false;
            }
            if (dk5==false)
            {
                lbDescription.Visible = true;
            }
            else { lbDescription.Visible = false; }
            if (dk6 == false)
            {
                lbIntroduce.Visible = true;
            }
            else
            {
                lbIntroduce.Visible = false;
            }
            if (dk7==false)
            {
                lbCategory.Visible = true;
            }
            else { lbCategory.Visible = false; }
            if (dk1 == true && dk2 == true && dk3 == true && dk4 == true && dk5 == true && dk6 == true && dk7 == true)
            {
                CongTy ct = new CongTy();
                ct.TenCongTy = txtCompany.Text;
                ct.LoaiCongTy = cbBusiness.SelectedItem.Text;
                int[] market = { 0, 0, 0, 0, 0, 0 };
                market = checkmarket(market);
                string strmarket = "";
                for (int i = 0; i < market.Count();i++ )
                {
                    strmarket = strmarket + market[i].ToString() + "+";
                }
                ct.ThiTruongChinh = strmarket;
                ct.IDNganh = int.Parse(cbIndustry.SelectedItem.Value);
                ct.TuKhoaSanPham = txtKeyProduct.Text;
                ct.SoLuongNhanVien = cbEmployees.SelectedItem.Text;
                ct.NamThanhLap = int.Parse(cbYear.SelectedItem.Text);
                ct.GioiThieuCongTy = txtIntroduct.Text;
                ct.TrangCongTy = txtWebsite.Text;
                if (UploadLogo.HasFile)
                {
                    ct.LogoCongTy = UploadLogo.FileName;
                    String strphoto = Server.MapPath("~/Images/Product/") + UploadLogo.FileName;
                    UploadLogo.SaveAs(strphoto);
                }
                else
                {
                    ct.LogoCongTy = pto;
                }
                if (UploadBrochoures.HasFile)
                {
                    ct.TaiLieu = UploadBrochoures.FileName;
                    string strBrochoure = Server.MapPath("~/Brochoure/") + UploadBrochoures.FileName;
                }
                else
                {
                    ct.TaiLieu = bro;
                }
                ct.KhuVucNhaMay = txtLocation.Text;
                ct.KichThuocNhaMay = cbFactorySize.SelectedItem.Text;
                ct.TongSoMuaHangNam = cbTotalAnnual.SelectedItem.Text;
                ct.SoLuongNhanVienRD = cbRDStaff.SelectedItem.Text;
                ct.SoLuongNhanVienQC = cbQCStaff.SelectedItem.Text;
                ct.GiayChungNhan = txtCertificate.Text;
                int[] manufactor = { 0, 0, 0 };
                manufactor = checkManufacturing(manufactor);
                String strManu = "";
                for (int i = 0; i < manufactor.Count();i++ )
                {
                    strManu = strManu + manufactor[i].ToString() + "+";
                }
                ct.HopDongSanXuat = strManu;
                ct.VonDieuLe = cbRegisterCapital.SelectedItem.Text;
                ct.LoaiQuyenSoHuu = cbOwnership.SelectedItem.Text;
                ct.NguoiDaiDien = txtLegalRepresentative.Text;
                ct.TongSoBanHangNam = cbTotalAnnualSale.SelectedItem.Text;
                ct.TyLeXuatKhau = txtExportPercentage.Text;
                int idCompany = CCongTy.getIdCompany(int.Parse(Session["IDDN"].ToString()));
                CCongTy.UpdateComnpany(ct,idCompany);
                Response.Redirect("~/PageUser/MbCompany.aspx");

            }   
        }
        private int[] checkManufacturing(int[] manufactor)
        {
            for (int i = 0; i < CheckBoxListContract.Items.Count; i++)
            {
                if (CheckBoxListContract.Items[i].Selected == true)
                {
                    manufactor[i] = 1;
                }
            }
            return manufactor;
        }
        private int[] checkmarket(int[] market)
        {
            for (int i = 0; i < ChecklistMarket.Items.Count;i++ )
            {
                if (ChecklistMarket.Items[i].Selected == true)
                {
                    market[i] = 1;
                }
            }
            return market;
        }
        protected void lbtnChangeCategory_Click(object sender, EventArgs e)
        {
            LoadCategoriesIntoListBox(gvLevel1, null);
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }
        protected void gvLevel1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }

        protected void gvLevel2_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }

        protected void gvLevel3_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }
        protected void cbLevel_CheckedChanged(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }
        protected void LinkDanhMucLevel1_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                gvLevel3.DataSource = null;
                gvLevel3.DataBind();
                LoadCategoriesIntoListBox(gvLevel2, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel2_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                LoadCategoriesIntoListBox(gvLevel3, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel3_Click(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }
        private bool LoadCategoriesIntoListBox(GridView control, int? parentCatID)
        {
            var cats = CCongTy.GetChildrenOfCategory(parentCatID);
            control.DataSource = cats;
            control.DataBind();
            return cats != null && cats.Count > 0;
        }
        private bool ExistCategoryInList(int IDCategory)
        {
            foreach (ListItem item in CategoryListBox.Items)
            {
                if (int.Parse(item.Value) == IDCategory)
                    return true;
            }
            return false;
        }

        private void AddCategoryToList(int IDCategory)
        {
            if (!ExistCategoryInList(IDCategory))
            {
                DanhMuc dm = CCongTy.GetCategoryByID(IDCategory);
                ListItem item = new ListItem();
                item.Value = dm.IDDanhMuc.ToString();
                item.Text = dm.TenDanhMuc;
                CategoryListBox.Items.Add(item);
            }
        }
        protected void btnAddCategory_OnClick(object sender, EventArgs e)
        {
            try
            {
                int id = 0;
                for (int i = 0; i < gvLevel1.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel1.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel2.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel2.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel3.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel3.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                lbThongBaoAddCategory.Text = "Add categories success.";
                lbThongBaoAddCategory.CssClass = "success";
                lbThongBaoAddCategory.Visible = true;
            }
            catch
            {
                lbThongBaoAddCategory.Text = "Add categories error.";
                lbThongBaoAddCategory.CssClass = "error";
                lbThongBaoAddCategory.Visible = true;
            }
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }
        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            lbThongBaoAddCategory.Visible = false;
            lbThongBaoAddCategory.Text = "";
        }

        protected void btRemoveSelect_Click(object sender, EventArgs e)
        {
            if (CategoryListBox.SelectedItem != null)
            {
                int index = CategoryListBox.SelectedIndex;
                CategoryListBox.Items.RemoveAt(index);
            }
        }
    }
}